// @flow
import React, { Component } from 'react'
import { Tabs, Tree } from 'antd'
import BomGrid from 'components/BomGrid'
import BomFaultGrid from 'components/BomFaultGrid'
import ConditionChart from 'components/ConditionChart'
import BomVarGrid from 'components/BomVarGrid'
import DevicePointView from 'components/DevicePointView'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './Bom.css'
import moment from 'moment'
const TabPane = Tabs.TabPane
const TreeNode = Tree.TreeNode
import { connect } from 'react-redux'

type Props = {
  deviceId: number,
  history: Object
}

type States = {
  boms: Array<Object>,
  deviceDatas: Array<Object>,
  varDatas: Array<Object>,
  eventDatas: Array<Object>
}
class Bom extends Component {
  props: Props
  state: States
  onSelect: () => void
  createNode: () => void
  constructor (props: Props) {
    super(props)
    this.state = {
      boms: [],
      deviceDatas: [],
      varDatas: [],
      eventDatas: []
    }
    this.onSelect = this.onSelect.bind(this)
    this.createNode = this.createNode.bind(this)
  }
  onSelect = (selectedKeys: Array<string>, info: string) => {
    console.log(selectedKeys);
    const selectProps = info.node.props
    if (selectedKeys.length > 0) {
      const deviceId = selectedKeys[0]
      this.getDevices(deviceId)
      if (selectProps.hasOwnProperty('children')) {
        this.getVars(deviceId, 'isComponent')
      } else {
        this.getVars(deviceId)
      }
      this.getEvents(deviceId)
    }
  }

  getDevices (deviceId) {
    universalFetch(`${__SERVICE_API__}device/devices/${deviceId}/boms?type=wide`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }

        this.setState({
          deviceDatas: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  componentWillMount () {
    const { deviceId } = this.props
    this.getBoms(deviceId)
    this.getEvents(deviceId)
    this.getDevices(deviceId)
    this.getVars(deviceId)
  }

  createNode (boms: Array<Object>) {
    return boms.map((bom, i) => {
      if (bom.children && bom.children.length > 0) {
        return <TreeNode title={bom.name} key={bom.id}>{this.createNode(bom.children)}</TreeNode>
      } else {
        return <TreeNode title={bom.name} key={bom.id} />
      }
    })
  }
  getBoms (deviceId: number) {
    universalFetch(`${__SERVICE_API__}device/devices/${deviceId}/boms?type=deep`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }

        this.setState({
          boms: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getEvents (deviceId: any) {
    universalFetch(`${__SERVICE_API__}device/devices/${deviceId}/events?orderBy=start_time desc`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          eventDatas: json.result.eventList.map((d, i) => {
            d['startTime'] = moment(d.startTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            d['endTime'] = moment(d.endTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            return d
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getVars (deviceId: any, isComponent) {
    let API
    if (isComponent) {
      API = `${__SERVICE_API__}device/devices/${deviceId}/monitors`
    } else {
      API = `${__SERVICE_API__}device/devices/${deviceId}/monitors?is-component=1`
    }
    universalFetch(API)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          varDatas: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  render () {
    const { boms, deviceDatas, varDatas, eventDatas } = this.state
    const { deviceId, history } = this.props
    return (
      <div className={styles['bom']}>
        <div className={styles['tree']}>
          {
            boms.length > 0
            ? <Tree
              showLine
              defaultExpandAll
              defaultSelectedKeys={[`${deviceId}`]}
              onSelect={this.onSelect}
            >
              {
                this.createNode(boms)
              }
            </Tree>
            : <div className={styles['no-data']}>暂无数据</div>
          }
        </div>
        <div className={styles['grid']}>
          <BomGrid {...{
            rowData: deviceDatas
          }} />
        </div>
        <div className={styles['tabs']}>
          <Tabs type='card'>
            <TabPane tab='故障信息' key='1'>
              <BomFaultGrid {...{
                history,
                rowData: eventDatas
              }} />
            </TabPane>
            {
              // <TabPane tab='部件工况' key='2'>
              //   <ConditionChart />
              // </TabPane>
              // <TabPane tab='部件变量' key='3'>
              //   <BomVarGrid {...{
              //     rowData: varDatas,
              //     history
              //   }} />
              // </TabPane>
            }
            <TabPane tab='设备测点' key='4'>
              <DevicePointView {...{
                deviceId
              }} />
            </TabPane>
          </Tabs>
        </div>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    deviceId: state.deviceCard.deviceData.id
  }
}
export default connect(mapStatesToProps, {})(Bom)
